import type { AxiosRequestConfig, AxiosResponse } from "axios";
import axios from "axios";

import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { getToken, removeToken } from "@/utils/auth";

/** app静态方法 */
// eslint-disable-next-line @typescript-eslint/no-extraneous-class
export default class AppUtil {
  static imgHost = "https://wadmin.xuming365.com/api/v1/resources";

  /**
   * config{
   * method post 或者get
   * url 接口地址
   * params 参数
   *}
   * sucessFun 访问成功执行的方法
   * loading_tip 加载中的提示文本
   * endFunc 无论成功或者失败，都要执行的方法
   * Func401  当后台返回401时执行的方法， 可以阻止自动登陆
   */
  static request(
    config: AxiosRequestConfig,
    sucessFun: any,

    endFunc?: (value: boolean) => void,
    failFunc?: (res: any) => void
  ): void {
    // !config.params && (config.params = {})
    // config.params.token = sessionStorage.getItem('token')
    // config.data = QueryString.stringify(config.data);
    let obj = getToken();
    let token = "";
    if (obj) {
      token = obj.accessToken;
    }

    // console.log('token', token);

    !config.headers && (config.headers = {});
    token && (config.headers["Authorization"] = token);
    const router = useRouter();
    axios(config)
      .then((res: AxiosResponse) => {
        // 防止正常提示被$toast.clear()清除
        const data = res.data;
        let success = true; // 成功或者失败
        if (data.code == 401 || data.code == 403) {
          // // resetRouter();
          // storageLocal().clear();
          // storageSession().clear();
          removeToken();
          console.log("code 401", router, useRouter());
          try {
            router.push("/login");
          } catch (error) {
            console.log(error);
            window.location.reload();
          }
        } else if (data.code != 200) {
          if (failFunc) {
            failFunc(data);
          } else {
            ElMessageBox.alert(data.msg || "网络异常", "提示", {
              // if you want to disable its autofocus
              // autofocus: false,
              confirmButtonText: "确定"
            });
          }

          success = false;
        } else {
          // 成功
          sucessFun(data);
        }
        endFunc ? endFunc(success) : "";

        // console.log('this.shop_info',this.shop_info);
      })
      .catch((error: any) => {
        // 防止提示被$toast.clear()清除
        if (!error.response) return;

        if (error.response.status == 401) {
          removeToken();
          return router.push("/login");
        }
        if (failFunc) {
          failFunc(error);
        } else if (error.response.data && error.response.data.errors) {
          ElMessageBox.alert(
            JSON.stringify(error.response.data.errors),
            "警告",
            {
              confirmButtonText: "确定"
            }
          );
        } else {
          ElMessageBox.alert(error.message || "异常错误", "警告", {
            confirmButtonText: "确定"
          });
        }
        endFunc ? endFunc(false) : "";
      });
  }

  /**
   * 获取阿里缩略图
   * @param url 原图地址
   * @param w 宽度
   */
  static getAliImgUrlByW(url, w = 200) {
    return `${AppUtil.imgHost}${url}?x-oss-process=image/resize,w_${w}`;
  }
  /**
   * 获取阿里缩略图
   * @param url 原图地址
   * @param h 高度
   */
  static getAliImgUrlByH(url, h = 200) {
    return `${AppUtil.imgHost}${url}?x-oss-process=image/resize,h_${h}`;
  }
  /**
   * 将秒数转为时分秒
   * @param sec 秒数
   */
  static get_hms(sec) {
    return `${parseInt(sec / 60 / 60)}时${parseInt(
      (sec / 60) % 60
    )}分${parseInt(sec % 60)}秒`;
  }
  /**date 返回 YYYY-MM-DD HH:mm:ss */
  static get_date(date: Date) {
    let day:number|string = date.getDate();
    if (day < 10) {
      day = "0" + day;
    }
    let month:number|string = date.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    let hour:number|string = date.getHours();
    if (hour < 10) {
      hour = "0" + hour;
    }
    let minute:number|string = date.getMinutes();
    if (minute < 10) {
      minute = "0" + minute;
    }
    let second:number|string = date.getSeconds();
    if (second < 10) {
      second = "0" + second;
    }
    return (
      date.getFullYear() +
      "-" +
      month +
      "-" +
      day +
      " " +
      hour +
      ":" +
      minute +
      ":" +
      second
    );
    // return dayjs(date).format("YYYY-MM-DD HH:mm:ss");
    // return date.format("YYYY-MM-DD HH:mm:ss");
  }
}
